<template>
  <div class="create-public-dialog">
    <el-dialog :visible.sync="dialogVisible" width="50%">
      <span slot="title">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item class="font-weight">博客</el-breadcrumb-item>
          <el-breadcrumb-item>博客发布</el-breadcrumb-item>
        </el-breadcrumb>
      </span>
      <!-- 表单 -->
      <el-form ref="formData" :rules="rules" :model="formData" label-width="100px" @submit.native.prevent>
        <el-form-item label="封面&摘要" prop="coverOrDescription">
          <el-radio-group v-model="formData.coverOrDescription">
            <el-radio label="图文"></el-radio>
            <el-radio label="无封面"></el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="formData.coverOrDescription == '图文'">
          <el-form-item label="">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item prop="img">
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadUrl"
                    :show-file-list="false"
                    name="file[]"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="formData.img" :src="formData.img" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item prop="description">
                  <el-input
                    type="textarea"
                    v-model="formData.description"
                    maxlength="256"
                    show-word-limit
                    resize="none"
                    :rows="4"
                    placeholder="摘要: 会在推荐、列表等场景外露，帮助读者快速了解内容"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="">
            <el-row>
              <el-col :span="24">
                <el-form-item prop="description">
                  <el-input
                    type="textarea"
                    v-model="formData.description"
                    maxlength="200"
                    show-word-limit
                    resize="none"
                    :rows="4"
                    placeholder="摘要: 会在推荐、列表等场景外露，帮助读者快速了解内容"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </template>
        <el-form-item label="文章标签" class="blog-form-tag" prop="tabList">
          <el-tag
            :key="tag"
            v-for="tag in formData.tabList"
            closable
            :disable-transitions="false"
            @close="tagClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="formData.tagVisible"
            v-model="formData.tagAddInput"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="tagConfirm"
            @blur="tagConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="tagShowInput">+ 添加文章标签</el-button>
        </el-form-item>
        <el-form-item label="分类专栏">
          <el-tag
            :key="index"
            v-for="(column, index) in formData.dynamicColumn"
            closable
            :disable-transitions="false"
            @close="columnClose(column)"
          >
            {{ column }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="formData.columnVisible"
            v-model="formData.columnAddInput"
            ref="saveColumnInput"
            size="small"
            @keyup.enter.native="columnConfirm"
            @blur="columnConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="columnShowInput">+ 新建分类专栏</el-button>
          <el-checkbox-group
            v-if="formData.dynamicColumnInit.length"
            @change="cheackboxChange"
            v-model="formData.columnCheckboxGroup"
            size="mini"
            class="column-list"
          >
            <el-checkbox
              :label="checkbox"
              v-for="(checkbox, index) in formData.dynamicColumnInit"
              :key="index"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="文章类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio label="原创"></el-radio>
            <el-radio label="转载"></el-radio>
            <template v-if="formData.type == '转载'">
              <el-form-item prop="linkInput" class="link-input">
                <el-input v-model="formData.linkInput" placeholder="请填写原文链接"></el-input>
              </el-form-item>
            </template>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布形式" prop="openLevel">
          <el-radio-group v-model="formData.openLevel">
            <el-radio label="公开"></el-radio>
            <el-radio disabled label="私密"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      loading: false,
      uploadUrl: window.INIT_CONFIG['baseUrl'] + '/upload',
      formData: {
        id: undefined,
        coverOrDescription: '图文',
        img: '',
        description: '',
        tagAddInput: '',
        tagVisible: false,
        tabList: [],
        columnAddInput: '',
        columnVisible: false,
        // 已选择的
        dynamicColumn: [],
        // 数据库存在的专栏
        dynamicColumnInit: [],
        // 打勾的专栏
        columnCheckboxGroup: [],
        type: '原创',
        linkInput: '',
        openLevel: '公开'
      },
      rules: {
        description: [{ required: true, message: '请输入文章摘要', trigger: 'blur' }],
        coverOrDescription: [{ required: true, message: '请选择封面形式', trigger: 'change' }],
        img: [{ required: true, message: '请上传图片', trigger: 'change' }],
        tabList: [
          // change是数据改变就会触发，如果写这个，在填写便签的时候就触发了。
          // blur是失去焦点触发验证
          // { type: 'array', required: true, message: '请至少填写一个标签', trigger: 'change' },
          { type: 'array', required: true, message: '请至少填写一个标签', trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择活动区域', trigger: 'change' }],
        openLevel: [{ required: true, message: '请选择活动区域', trigger: 'change' }],
        linkInput: [{ required: true, message: '请填写原文链接', trigger: 'blur' }]
      }
    }
  },
  methods: {
    showDialog(data) {
      this.dialogType = data.dialogType
      this.formData = Object.assign({}, this.formData, data.data)
      // 后端只返回已选择的，这赋值是为了编辑的时候打勾
      this.formData.columnCheckboxGroup = this.formData.dynamicColumn
      this.getColumnInit()
      this.dialogVisible = true
      this.clearValidate()
    },
    cheackboxChange() {
      let { dynamicColumn, columnCheckboxGroup, dynamicColumnInit } = this.formData
      for (let i = 0; i < dynamicColumnInit.length; i++) {
        let index = columnCheckboxGroup.indexOf(dynamicColumnInit[i])
        if (index > -1) {
          // 有选中
          dynamicColumn.push(dynamicColumnInit[i])
        } else {
          // 没有选中
          let findIndex = dynamicColumn.indexOf(dynamicColumnInit[i])
          findIndex > -1 && dynamicColumn.splice(findIndex, 1)
        }
      }
      this.formData.dynamicColumn = Array.from(new Set(dynamicColumn))
    },
    handleAvatarSuccess(res, file) {
      URL.createObjectURL(file.raw)
      this.formData.img = file.response.data.succMap.url
    },
    beforeAvatarUpload(file) {
      const type = file.type
      const isLimit = file.size > 300 * 1024 ? true : false
      if (isLimit) {
        this.$message.error('上传图片太大')
        return
      }
      // 数据库不支持
      if (type == 'image/webp') {
        this.$message.error('上传图片格式不能为image/webp!')
        return
      }
      return !isLimit
    },
    tagClose(tag) {
      this.formData.tabList.splice(this.formData.tabList.indexOf(tag), 1)
    },
    tagConfirm() {
      let tagAddInput = this.formData.tagAddInput
      let isExist = this.formData.tabList.includes(tagAddInput)
      if (tagAddInput && !isExist) {
        this.formData.tabList.push(tagAddInput)
      } else if (isExist) {
        this.$message({
          message: '该标签已经存在',
          type: 'warning'
        })
        return
      }
      this.formData.tagVisible = false
      this.formData.tagAddInput = ''
    },
    tagShowInput() {
      this.formData.tagVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    columnClose(tag) {
      const checkbox = []
      const dynamicColumn = this.formData.dynamicColumn
      dynamicColumn.splice(dynamicColumn.indexOf(tag), 1)
      for (let i = 0; i < dynamicColumn.length; i++) {
        if (this.formData.dynamicColumnInit.includes(dynamicColumn[i])) {
          checkbox.push(dynamicColumn[i])
        }
      }
      this.formData.columnCheckboxGroup = checkbox
    },
    columnConfirm() {
      let columnAddInput = this.formData.columnAddInput
      // 不能添加重复以及存在的专栏
      let isExist = this.formData.dynamicColumnInit.includes(columnAddInput)
      if (columnAddInput && !isExist) {
        this.formData.dynamicColumn.push(columnAddInput)
      } else if (isExist) {
        this.$message({
          message: '该专栏已经存在',
          type: 'warning'
        })
        return
      }
      this.formData.columnVisible = false
      this.formData.columnAddInput = ''
    },
    columnShowInput() {
      this.formData.columnVisible = true
      this.$nextTick(() => {
        this.$refs.saveColumnInput.$refs.input.focus()
      })
    },
    getColumnInit() {
      this.$ajax({
        url: this.$ajax.setUrl('/column'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          const columnNameList = []

          const columnList = data.data
          for (let i = 0; i < columnList.length; i++) {
            columnNameList.push(columnList[i].name)
          }
          this.formData.dynamicColumnInit = columnNameList
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    // 提交表单
    submitForm() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          // 向后端发送数据 post
          // 发送什么数据呢？
          this.loading = true
          let url = ''
          if (this.dialogType === 'add') {
            url = '/article/create'
          } else {
            url = `/article/${this.$route.query.articleId}`
          }

          this.$ajax({
            // 添加接口就可以了。
            url: this.$ajax.setUrl(url),
            // 新发布的文章用post请求，修改的用put请求。
            method: this.dialogType === 'add' ? 'post' : 'put',
            data: this.$ajax.setData(this.getParams())
          })
            .then(({ data }) => {
              if (data && data.code === 0) {
                this.loading = false
                this.dialogVisible = false
                this.$message({
                  message: '发布成功',
                  type: 'success'
                })
                // 直接跳转到这个文章查看,直接跳有点突然，给一个过渡比较好
                console.log(data.data)
                this.$emit('changeShowSuccess', { show: true, data: data.data })
              } else {
                this.loading = false
                this.$message.error(data.data || data.msg)
              }
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    getParams() {
      // 需要传递给后端的参数
      const {
        id,
        type,
        openLevel,
        tabList,
        coverOrDescription,
        description,
        img,
        linkInput,
        contentEditor,
        title,
        dynamicColumn
      } = this.formData
      let params = {
        id,
        type,
        tabList,
        coverOrDescription,
        description,
        openLevel,
        contentEditor,
        title
      }

      if (dynamicColumn.length !== 0) {
        params.dynamicColumn = dynamicColumn
      }

      if (coverOrDescription === '图文') {
        params.img = img
      }
      if (type === '转载') {
        params.linkInput = linkInput
      }
      return params
    },
    clearValidate() {
      this.$nextTick(() => {
        this.$refs['formData'].clearValidate()
      })
    }
  }
}
</script>

<style lang="scss">
#modules-blog-create {
  .create-public-dialog {
    .el-dialog {
      min-width: 660px;
    }
    .font-weight {
      font-weight: bold;
    }
    .column-list {
      border: 1px solid #e8e8ee;
      padding-left: 10px;
    }

    // 设置添加标签的样式下面三个class
    .el-tag + .el-tag {
      margin-left: 10px;
    }
    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
    }
    .input-new-tag {
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }
    .link-input {
      display: inline-block;
    }

    // 上传头像css
    .avatar-uploader {
      // width: 100%;
      height: 99px;
    }
    .avatar-uploader .el-upload {
      width: 100%;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100%;
      height: 96px;
      line-height: 96px;
      text-align: center;
    }
    .avatar {
      width: 100%;
      height: 96px;
      display: block;
    }
  }
}
</style>
